<template>
  <div class="user-management">
    <!-- 搜索栏 -->
    <el-card shadow="never" class="search-box">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="账号">
          <el-input
            v-model="searchForm.account"
            placeholder="输入账号"
            clearable
          />
        </el-form-item>
        <el-form-item label="专业">
          <el-input
            v-model="searchForm.major"
            placeholder="输入专业"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="searchForm.status">
            <el-radio-button :label="1">启用</el-radio-button>
            <el-radio-button :label="0">禁用</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-button type="primary" @click="loadUsers">搜索</el-button>
      </el-form>
    </el-card>

    <!-- 用户表格 -->
    <el-table :data="userList" row-key="id" border stripe v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="account" label="账号" />
      <el-table-column prop="userName" label="姓名" />
      <el-table-column label="状态" width="100px">
        <template #default="{ row }">
          <el-tag :type="row.active ? 'success' : 'danger'">
            {{ row.active ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="major" label="专业" width="120" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" @click="showButton(row)">查看</el-button>
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button
            size="small"
            :type="row.active ? 'danger' : 'success'"
            @click="toggleStatus(row)"
          >
            {{ row.active ? "禁用" : "启用" }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="pagination"
      v-model:current-page="pagination.current"
      v-model:page-size="pagination.size"
      :total="pagination.total"
      :page-sizes="[10, 20, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="loadUsers"
      @current-change="loadUsers"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import userApi from "@/api/user";
import apiClient from "@/axios";
import router from "@/router";
import { ElMessage, ElMessageBox } from "element-plus";

// 搜索表单
const searchForm = ref({
  account: "",
  major: "",
  status: null,
});

// 专业选项（示例）
const majorOptions = ["计算机科学", "电子信息", "机械工程", "工商管理"];

// 分页配置
const pagination = ref({
  current: 1,
  size: 10,
  total: 0,
});

// 用户列表数据
const userList = ref([]);
const loading = ref(false);

// 加载用户数据
const loadUsers = async () => {
  try {
    loading.value = true;
    const params = {
      ...searchForm.value,
      page: pagination.value.current,
      pageSize: pagination.value.size,
    };
    // const res = await userApi.getUserList(params);
    const res = await apiClient.post("/users/pageSelect", params);
    userList.value = res.data.records;
    pagination.value.total = res.data.total;
  } finally {
    loading.value = false;
  }
};

// 切换用户状态
const toggleStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.active ? "禁用" : "启用"}该用户吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );
    await updateStatus(row.id, row.active ? 0 : 1);
    ElMessage.success("状态更新成功");
    loadUsers();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error(error.message || "操作失败");
    }
  }
};
const updateStatus = async function (userId, newStatus) {
  try {
    const response = await apiClient.put(`/users/${userId}/status`, {
      active: newStatus,
    });
    return response.data; // 返回更新后的数据
  } catch (error) {
    throw new Error(error.response?.data?.message || "更新状态失败");
  }
};

// 编辑用户
const showButton = (row) => {
  // 跳转到编辑页或打开弹窗
  router.push({ name: "userManage", query: { id: row.id, type: "details" } });
};
const handleEdit = (row) => {
  // 跳转到编辑页或打开弹窗
  router.push({ name: "userManage", query: { id: row.id, type: "update" } });
};

// 初始化加载
onMounted(() => {
  loadUsers();
});
</script>

<style scoped>
.user-management {
  padding: 20px;
}
.search-box {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>